<template>
<kb-layout> 
	<view id="j_page" class="cu-chat">
	<view class="brokerbar" v-if="tobroker!=='undefined' && tobroker?.iscompany && tobroker.iscompany==1">
		<view class="broker">
			<view class="logo u-m-r-10">
				<up-avatar :src="tobroker?.avatar??ee.account.logo" shape="square"></up-avatar>
				 
			</view>
			<view class="name">
				<u-text :text="(tobroker?.truename!='')?tobroker?.truename: tobroker.nickname" :bold="true" lines="1"></u-text>
				<u-text color="#999" size="11" :text="tobroker?.mobile??''"></u-text>
			</view>
		</view>
		<view class="action">
			 <view click="phone">
				<u-button @click="callPhone" 
				 shape="circle"
				icon="phone" color="#DEEEFF">				 
				</u-button>
			</view>
		</view>
	</view>
	 <view  class="cu-info round"
		@click="onFetchHistoryMessage">
	    <text class="iconfont icon-yuyue text-red "></text> 
	    查看更多历史记录
	  </view>	
	  <view  v-for="(item ,index) in messageList" :key="index">
	  <kb-tallk-message :msginfo="item"></kb-tallk-message>
	  </view>
	  
	  <view class="sendbox">
		<view class="form-line-left">
			  <up-icon @click="this.showhx=!this.showhx" name="list-dot" size="30"></up-icon>
		</view>
		<view class="form-line">	
			<up-button v-if="ee.security?.closetallk==1" class="button" 
				size="small"
			  @click="this.showhx=!this.showhx">常见问题提问</up-button>
			 
			<input v-else class="input" v-model="formInput"			 
			 @confirm="sendTextMessage"  placeholder="请输入内容"  /> 
		</view>
		<view  class="form-line-right">
			<up-button @click="sendTextMessage" type="primary" size="small" text="发送"></up-button>
		</view>
	  </view>
	  <!-- <u-button @click="openChat" text="联系客服"></u-button> -->
	</view>
	<!-- 弹出bindmobile -->
	<kb-bind-mobile :showModal="ee.showBindMobile"></kb-bind-mobile>	 
		
	<up-action-sheet
				:show="showhx"
				@close="showhx=false"
				title="发送常用语"
				:round="10"
			>
		 <view class="sheet">
			 <!-- 多选 -->
			 <up-list height="400">
				 <up-list-item  v-for="(item, index) in helloList"
				  :key="index">
				<up-cell icon="·"
				 :icon-style="{fontSize:'60rpx'}"
				 :custom-style="{textAlign:'left'}" 
				 :name="index"
				 :title="item.title"
				  :isLink="true" @click="onClickHellowText"
				  arrow-direction="right"></up-cell>
				 </up-list-item>
				 
			 </up-list>
		 </view>	 
	</up-action-sheet> 
</kb-layout>
</template>

<script>
	import util from "@/common/tools/utils.js";
    import {ims} from "./ims.js"
	export default {
		data() {
			return {
				hid: 0, //房源id
				house: undefined,
				showhx: false,
				helloList:[
					//{id:1,title:'这套房子的建筑面积是多少 是房产证上的数据吗？'},
					//{id:2,title:'还有更多的信息吗'}
				],
				formInput:'',
				broker: undefined,
				tobroker: undefined, 
				messageList:[],
				page: 1,
				totalpage:0,
				lastid :0,
				aihelpid: 0, //发送的自助问答id
			} 
		},
		computed:{
			history_query: function(  ){						 
				return {
				  fromAccount : this.broker?.openid,
				  fromAccountPic: this.broker?.avatar,
				  toAccount: this.tobroker?.openid,
				  toAccountPic: this.tobroker?.avatar,
				  hid: this.hid,
				  aihelpid: this.aihelpid,
				}
			} 
		}, 
		methods: {
		 callPhone(){
			 this.ee.callPhone(this.tobroker?.mobile??'')
		 },
		 onFetchHistoryMessage(){
			 
			 let page = this.page +1;
			 let query_params = this.history_query;
			 query_params.total = this.totalpage;
			 query_params.page = page;
			 if(page > this.totalpage){
				 uni.showToast({
					 icon:"none",
				 	title: '没有更多记录'
				 })
				 return false;
			 }
		 
			 ims.history_message(query_params)
			 .then((data)=>{
					console.log('lishi',data)
			     let mlist = ims.message_formact(data.msglist);
				 this.page = page;
				 this.messageList = mlist.concat(this.messageList)
		 
			})
		 },
			onClickHellowText(e){
				console.log(e)
				this.showhx = false;
				this.aihelpid = this.helloList[e.name].id;
				this.formInput =  this.helloList[e.name].title;
				var msgcontent = this.helloList[e.name].content;
				this.sendTextMessage( function(that){
					//把智能回复的内容发送
					let msginfo = ims.message_type_text(that.tobroker.openid,
					that.broker.openid  , msgcontent)
					 var params  = that.history_query;							
					ims.send_message(  Object.assign(msginfo, params) ).then( ()=>{
						 //显示到聊天记录
						params.lastid = that.lastid;
						ims.send_me_last_msg( params).then(ret=>{											 
							 
								 if(ret?.id){
									 that.lastid = ret.id;
									 let message = ims.message_formact(ret)[0];
									 that.messageList  =  that.messageList.concat(message)
								 }
							 setTimeout(()=>{that.pageScrollToBottom()},100); 
						})
						//拉取消息end
					})
				})
				
			},
			openChat(){
				wx.openCustomerServiceChat({
				  extInfo: {url: 'https://work.weixin.qq.com/kfid/kfcaf508164bca4d805'},
				  corpId: 'wwcd12a319f1bfb982',
				  success(res) {
					  console.log('打开成功')
				  },
				  fail(error){
					  console.log(error)
				  }
				})
			},
			sendTextMessage : function(callback){
			     var msgcontent =  this.formInput;	
				  
			      if(!msgcontent ){
			        uni.showToast({
			          icon: 'none',         
			          title: '请输入内容'
			        })
			        return false;
			      }
				  this.formInput = "";
				  var params = this.history_query;
				  params.lastid = this.lastid;
			     ims.send_me_last_msg( params).then(ret=>{
					  
					 if(ret?.id){
						 this.lastid = ret.id;
						 let message = ims.message_formact(ret)[0];
						 this.messageList  =  this.messageList.concat(message)
					 }
					 return ret;
				 }).then( ret =>{
					 //发文字消息
					 let msginfo = ims.message_type_text(this.broker.openid, 
					  this.tobroker.openid, msgcontent)
					  var base  = this.history_query;
					 		
					 return ims.send_message(  Object.assign(msginfo, base) )
				 }) 
			     .then((res)=>{
					 if(typeof callback  ==='function' ){
						 callback( this );
					 }
				    //滚动页面到底部
			        setTimeout(()=>{this.pageScrollToBottom()},100);
			       
			         //self._megary_msg_list(res)
					 let message = ims.message_formact(res)[0];
					 message.thumb = this.broker.avatar;
					 message.whocss =  "aui-chat-right" ;
					 this.messageList = this.messageList.concat(message)
			      })
			  },
			  // 假设你在某个方法中需要滚动到页面底部
			  pageScrollToBottom() {
			    uni.createSelectorQuery().select('#j_page').boundingClientRect(data => {
			      if (data) { 
			        uni.pageScrollTo({
			          scrollTop: data.height,
			          duration: 300 // 动画时长，默认300ms
			        });
			      }
			    }).exec();
			  }
		},
		onLoad(option) {
			this.hid = option.hid || 0;
			var bid =  option.bid || 0;
			var toopenid = option.toopenid ||'';
			var hid = this.hid;
			this.ee.getWxappAccount();
			
			
			this.ee.getBroker().then(ret=> {
				this.broker = ret ; 
				console.log(this.broker);
				return util.getModuleData("webfront/getbroker",{bid:bid,hid:hid,toopenid: toopenid})
			}) 
			 .then(ret => {
				 if(!ret){
					 uni.showToast({
					 	icon:'none',
					 	title:'不能和自己对话'
					 });
					 uni.navigateTo({url: "/pages/index"} )
					 return new Promise((resolve,reject)=>{
						 reject()
				    })
				 }
				this.tobroker = ret; 
				if(ret.openid == this.broker.openid){					 
					return new Promise((resolve,reject)=>{
						uni.showToast({
								icon:'error',
								title:'不能和自己对话'
							})
						reject()
				    })
				} 
				util.getModuleData("zufang/wenda", {hid:this.hid}).then(ret=>{
					this.helloList = ret;			 
				})
				
			    return util.getModuleData("showhouse/index",{id: this.hid})
				 
			})		  
			 .then(ret=>{
				 console.log('得到房子信息', ret, typeof ret)
				 if( ! ret?.id ){
					 console.log('没有房源信息')
					 return false;
				 }
				 this.house = ret;
				
				 return ims.onSendHouse(
						 this.broker.openid, 
						 this.tobroker.openid, 
						 ims.house_to_msg(ret),
						  this.history_query );
			})
			.then(ret=>{ 
				console.log('进入步骤获取历史记录', ret)
				  //获取聊天记录最后10条
				return ims.history_message( this.history_query  )
			}).then( (messages)=>{ 
				var len = messages.msglist.length
				var lastinfo = messages.msglist[len-1]
			   //console.log(lastinfo)
				this.lastid = lastinfo.id
				 console.log("聊天消息=>",messages)
				 this.messageList = ims.message_formact( messages.msglist);
				 this.totalpage = messages.totalpage;
				 console.log("聊天消息 format=>", this.messageList, this.totalpage)
				setTimeout(()=>{this.pageScrollToBottom()},100);
			}).catch( e=>{
				console.log('出现异常', e);
				//uni.showToast( {icon:'error', title:'出现异常'})
			})
			 
		}
	}
</script>

<style>
 @import url("../../static/tallk.css");
 @import "./my.scss";
 .cu-chat{
	 padding-bottom: 60px;
 }
 .brokerbar{
 	display: flex;
 	width: 100%;
 	height: 50px;
 	flex-direction: row;
 	justify-content: space-between;
 	align-items: center;
 	vertical-align: middle;
  
 	background: #fff;
 	z-index: 999;
 	border-bottom: 1px solid #dadada;
 	}
 	 .brokerbar .broker{
 		display: flex;
 		margin-left: 20px;
 		align-items: center;
 		vertical-align: middle;
 	}	
 	 .brokerbar .action{
 		display: flex;
 		margin-right: 10px;
 		align-items: center;
 		vertical-align: middle;
 	}
 
</style>
